<!DOCTYPE html>
<html>
<head>
  <title>Product Search</title>
</head>
<body>
  <label for="search">Search:</label>
  <input type="text" id="search">
  <button id="searchBtn">Search</button>
  <div id="result"></div>

  <script>
    // 获取页面元素
    const searchBox = document.getElementById("search");
    const searchBtn = document.getElementById("searchBtn");
    const resultDiv = document.getElementById("result");

    // 添加事件监听器
    searchBtn.addEventListener("click", searchProducts);

    // 查询商品函数
    function searchProducts() {
      const xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
          const products = JSON.parse(this.responseText);
          const searchTerm = searchBox.value.toLowerCase();
          const matchingProducts = products.filter(product => {
            const name = product.name.toLowerCase();
            const description = product.description.toLowerCase();
            return name.includes(searchTerm) || description.includes(searchTerm);
          });
          displayProducts(matchingProducts);
        }
      };
      xhr.open("GET", "products.json");
      xhr.send();
    }

    // 显示查询结果函数
    function displayProducts(products) {
      if (products.length > 0) {
        const productList = products.map(product => {
          return `<div>
                    <h3>${product.name}</h3>
                    <p>${product.price}</p>
                    <p>${product.description}</p>
                  </div>`;
        }).join("");
        resultDiv.innerHTML = productList;
      } else {
        resultDiv.innerHTML = "No matching products found.";
      }
    }
  </script>
</body>
</html>